<?php

namespace api\models;

use api\components\BaseModel;
use api\exceptions\OperateException;
use common\components\Exception;
use Yii;
use yii\rbac\Role;

class UserInfo extends BaseModel
{
    const SCENARIO_USER_REGISTER = 'user_register';
    const SCENARIO_USER_LOGIN = 'user_login';

    public $username;
    public $password;
    public $rePassword;
    public $email;
    public $mobile;

    public function scenarios()
    {
        return [
            self::SCENARIO_USER_REGISTER => ['username', 'password', 'rePassword', 'email', 'mobile',],
            self::SCENARIO_USER_LOGIN => ['username', 'password',],
        ];
    }

    public function rules()
    {
        return [
            [['username', 'password', 'rePassword'], 'trim'],
            [['username', 'password', 'rePassword'], 'required'],
        ];
    }

    /**
     * 用户登陆
     * @throws \yii\base\InvalidConfigException
     * @throws \common\components\Exception
     */
    public function login()
    {
        if (!$this->validate())
            static::getErrorMessage($this);
        /** @var \filsh\yii2\oauth2server\Module $module */
        $module = Yii::$app->getModule('oauth2');
        //获取oauth框架的请求体,并覆盖其请求方式
        $filshRequest = $module->getRequest();
        $filshRequest->request = array_merge(Yii::$app->request->post(), ['grant_type' => 'password', 'client_id' => 'testclient', 'client_secret' => 'testpass']);
        $module->set('request', $filshRequest);
        $oauthResponse = $module->getServer()->handleTokenRequest()->getParameters();
        if (!isset($oauthResponse['access_token']))
            throw new Exception('USER_GENERATE_ACCESS_TOKEN_FAILED');
        return [
            'accessToken' => $oauthResponse['access_token'],
            'expiresIn' => $oauthResponse['expires_in'],
            'tokenType' => $oauthResponse['token_type'],
            'refreshToken' => $oauthResponse['refresh_token'],
        ];
    }

    /**
     * REFRESH_TOKEN
     * @throws \yii\base\InvalidConfigException
     * @throws Exception
     */
    public function refreshToken()
    {
        if (!$this->validate())
            static::getErrorMessage($this);
        /** @var \filsh\yii2\oauth2server\Module $module */
        $module = Yii::$app->getModule('oauth2');
        //获取oauth框架的请求体,并覆盖其请求方式
        $filshRequest = $module->getRequest();
        $filshRequest->request = ['grant_type' => 'refresh_token', 'client_id' => 'testclient', 'client_secret' => 'testpass', 'refresh_token' => $this->refreshToken];
        $module->set('request', $filshRequest);
        $oauthResponse = $module->getServer()->handleTokenRequest()->getParameters();
        if (!isset($oauthResponse['access_token']))
            throw new Exception('USER_GENERATE_ACCESS_TOKEN_FAILED');
        return [
            'accessToken' => $oauthResponse['access_token'],
            'expiresIn' => $oauthResponse['expires_in'],
            'tokenType' => $oauthResponse['token_type'],
            'refreshToken' => $oauthResponse['refresh_token'],
        ];
    }

    /**
     * 用户注册
     * @return array
     * @throws Exception
     * @throws \Exception
     */
    public function register()
    {
        if (!$this->validate())
            static::getErrorMessage($this);
        $user = new User();
        $user['username'] = $this->username;
        $user['status'] = User::STATUS_ACTIVE;
        $user['role'] = User::ROLE_DEFAULT;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        if ($user->save(false)) {
            $role = new Role();
            $role->name = isset(User::ROLE_ARR[$user['role']]) ? User::ROLE_ARR[$user['role']] : '未知';
            Yii::$app->authManager->assign($role, Yii::$app->db->getLastInsertID());
        }
        return ['res' => true];
    }
}